package com.farm.model.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup()
        .lookupClass());

    /**
     * 生成随机数
     *
     * @param length
     * @return
     * @author zhangBin
     * @date 2017年12月8日
     */
    public static int getRandNum(int length) {
        int randNum = (int)((Math.random() * 9 + 1) * length);
        return randNum;
    }


    /**
     * 吧当前日期的时分秒设置为0
     *
     * @param date
     * @return
     * @author zhangBin
     * @date 2018年2月5日
     */
    public static Date getTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 手机号校验
     *
     * @param mobile
     * @return
     */
    private static final Pattern MOBILE_PATTERN = Pattern.compile("^[1][1-9][0-9]{9}$");

    public static boolean isMobile(String mobile) {
        Matcher m = MOBILE_PATTERN.matcher(mobile);
        return m.matches();
    }

    private static final int[] DEFALUT_PAGE = new int[] {1, 10};


    private static final Pattern TAX_PAYER_NUM_PATTERN = Pattern.compile("^[A-Za-z0-9]{15,20}$");

    /**
     * 校验发票信用代码格式, 为空不校验(信用代码可以为空)
     *
     * @param invoiceCode
     * @return
     */
    public static boolean isValidTaxPayerNumber(String invoiceCode) {
        return StringUtils.isEmpty(invoiceCode) ? true : TAX_PAYER_NUM_PATTERN.matcher(invoiceCode)
            .matches();
    }

    private static final Pattern BRACKETS_PATTERN = Pattern.compile("(?<=[\\(\\（]).*(?=[\\)\\）])");

    /**
     * 提取中英文括号内内容
     */
    public static String extractFromBracketsIfExists(String content) {
        if (StringUtils.isEmpty(content)) {
            return StringUtils.EMPTY;
        }
        Matcher matcher = BRACKETS_PATTERN.matcher(content);
        return matcher.find() ? matcher.group() : content;
    }

    /**
     * 把参数根据ascii从小到大排序并拼接参数
     *
     * @param map
     * @return
     */
    public static String getAsciiOrder(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString()
                        .compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (StringUtils.isNotBlank(val)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return "";
        }
        return result;

    }


    /**
     * 输出内容
     *
     * @param response
     * @param contentType
     * @param content
     */
    private static void writeResponse(HttpServletResponse response, String contentType, String content) {
        try {
            response.setContentType(contentType + ";charset=UTF-8");
            response.getWriter()
                .print(content);
        } catch (IOException e) {
            logger.error("输出出错", e);
        }
    }

    /**
     * @param str
     * @return boolean
     * @Description 判断这个对象是否是map或者list
     * @author yumo
     * @date 2018-7-13 16:35
     */
    public static boolean isNotObjectOrList(Object str) {
        boolean flag = true;
        if (str instanceof Map || str instanceof List) {
            flag = false;
        }
        return flag;
    }

    /**
    *正整数，正小数校验
    *@Author ziming
    *@Date 2018/11/6 16:55
    */
    private static final Pattern DECIMAL_PATTERN = Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])");

    public static boolean isDecimal(String margin) {
        Matcher m = DECIMAL_PATTERN.matcher(margin);
        return m.matches();
    }
}
